package jsr292.java.lang.invoke;

import java.lang.reflect.Array;

import jsr292.weaver.Debug;
import jsr292.weaver.opt.OptimizerContext;
import jsr292.weaver.opt.OptimizerSnippets;
import jsr292.weaver.opt.OptimizerVarAllocator;

public class MHArrayElementSetter extends MethodHandle {
    private final Class<?> arrayClass;
    
    public MHArrayElementSetter(Class<?> arrayClass) {
        super(MethodType.methodType(void.class, arrayClass, int.class, arrayClass.getComponentType()));
        this.arrayClass = arrayClass;
    }
  
    @Override
    public Object $invoke$(Object o1, Object o2, Object o3) throws Throwable {
        Array.set(o1, (Integer)o2, o3);
        return null;
    }
    
    @Override
    public boolean isWeavable(Class<?> classBeingRedefined) {
        return true;
    }
    
    @Override
    public void weave(OptimizerContext context, OptimizerVarAllocator allocator) {
        if (Debug.DEBUG) {
            Debug.checkAllocator(allocator, this);
        }
        
        OptimizerSnippets.arraySetter(context, allocator, arrayClass);
    }
}
